import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '', // 保持空，所有路径手动加/api前缀
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// ===================== 申请相关接口 =====================
export interface ApplicationForm {
  applicationType: string
  classroomType: string
  userId: number
  applyDate: string
  startTime: string
  endTime: string
  purpose: string
  expectedPeople: number
  equipmentNeeds: string
  classroomIds: number[]
}

export interface ApplicationItem {
  applicationId: number
  userName: string
  applicationType: string
  classroomType: string
  expectedPeople: number
  applyDate: string
  startTime: string
  endTime: string
  purpose: string
  equipmentNeeds: string
  status: string
  createTime: string
  approverName?: string
  approveTime?: string
  approveComment?: string
  allocatorName?: string
  allocateTime?: string
}

export interface ApplicationQuery {
  pageNum?: number
  pageSize?: number
  keyword?: string
  applicationType?: string
  classroomType?: string
  status?: string
  userId?: number
}

export interface ApplicationResponse {
  list: ApplicationItem[]
  total: number
  pageNum: number
  pageSize: number
}

// 分页查询申请列表
export function getMyApplications(params: ApplicationQuery) {
  return api.get('/api/classroom/page', { params })
}

// 待审批申请列表
export function getPendingApplications(params: { userRole: string, userId: number }) {
  return api.get('/api/classroom/pending', { params })
}

// 待分配申请列表
export function getToAllocateApplications(params: ApplicationQuery) {
  return api.get('/api/classroom/to-allocate', { params })
}

// 获取申请详情
export function getApplicationDetail(applicationId: number) {
  return api.get(`/api/classroom/${applicationId}`)
}

// 获取带申请人姓名的详情
export function getApplicationDetailWithUserName(applicationId: number) {
  return api.get(`/api/classroom/vo/${applicationId}`)
}

// 获取全流程详情
export function getApplicationFullDetail(applicationId: number) {
  return api.get(`/api/classroom/full/${applicationId}`)
}

// 提交教室申请
export function submitClassroomApplication(data: ApplicationForm) {
  return api.post('/api/classroom/apply', data)
}

// 取消申请
export function cancelApplication(applicationId: number) {
  return api.put(`/api/classroom/${applicationId}/cancel`)
}

// 单个审批
export function approveApplication(applicationId: number, data: { approverId: number, approvalStatus: string, approvalOpinion?: string }) {
  return api.post(`/api/classroom/${applicationId}/approve`, data)
}

// 批量审批
export function batchApproveApplications(data: { applicationIds: number[], approverId: number, approvalStatus: string, approvalOpinion?: string }) {
  return api.post('/api/classroom/batch-approve', data)
}

// 单个分配
export function allocateClassrooms(applicationId: number, data: { allocatorId: number, classroomId: number }) {
  return api.post(`/api/classroom/${applicationId}/allocate`, data)
}

// 批量分配
export function batchAllocateClassrooms(data: { applicationIds: number[], allocatorId: number, classroomIds: number[] }) {
  return api.post('/api/classroom/batch-allocate', data)
}

// 获取已分配教室详情
export function getAllocatedClassrooms(applicationId: number) {
  return api.get(`/api/classroom/${applicationId}/classrooms`)
}

// ===================== 统计相关接口 =====================
export interface StatisticsData {
  totalApplications: number
  pendingApplications: number
  approvedApplications: number
  allocatedApplications: number
  approvalRate: number
  allocationRate: number
}

// 获取统计卡片数据
export function getStatistics() {
  return api.get('/api/classroom/statistics')
}

export interface ChartDataItem {
  date: string
  applications: number
  processed: number
}

// 获取折线图数据
export function getChartData(params: { period: number }) {
  return api.get('/api/classroom/statistics/chart', { params })
}

export interface DetailedStatItem {
  date: string
  newApplications: number
  approved: number
  allocated: number
  rejected: number
  avgProcessTime: number
  satisfaction: number
}

// 获取详细统计表格数据
export function getDetailedStats(params: { start?: string, end?: string }) {
  return api.get('/api/classroom/statistics/detail', { params })
}

// ===================== 其他接口可按需补充 =====================

// 查询教室列表
export function getClassroomList(params: { pageNum?: number, pageSize?: number, classroomType?: string, capacity?: number, status?: string }) {
  return api.get('/api/classroom/list', { params })
}

// 查询可用教室
export function getAvailableClassrooms(params: { date: string, startTime: string, endTime: string, classroomType?: string, capacity?: number }) {
  return api.get('/api/classroom/available', { params })
}

// 新增教室
export function addClassroom(data: {
  classroomName: string,
  campus?: string,
  building: string,
  floor: number,
  capacity: number,
  classroomType: string,
  equipmentList?: string[],
  status?: string
}) {
  return api.post('/api/classroom/add', data)
}

// 查询教室详情
export function getClassroomDetail(classroomId: number) {
  return api.get(`/api/classroom/${classroomId}`)
}

// 更新教室
export function updateClassroom(classroomId: number, data: {
  classroomName: string,
  campus?: string,
  building: string,
  floor: number,
  capacity: number,
  classroomType: string,
  equipmentList?: string[],
  status?: string
}) {
  return api.put(`/api/classroom/${classroomId}`, data)
}

// 删除教室
export function deleteClassroom(classroomId: number) {
  return api.delete(`/api/classroom/${classroomId}`)
}

// 删除分配记录
export function deleteAllocation(allocationId: number) {
  return api.delete(`/api/classroom/allocation/${allocationId}`)
}

export default api 